/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.appletShow.controller;

import com.fzhucc.annotation.AnonymousAccess;
import com.fzhucc.annotation.Log;
import com.fzhucc.annotation.rest.AnonymousGetMapping;
import com.fzhucc.annotation.rest.AnonymousPostMapping;
import com.fzhucc.modules.appletShow.domain.dto.CmsServiceCodeDto;
import com.fzhucc.modules.appletShow.domain.dto.CmsServiceDto;
import com.fzhucc.modules.appletShow.domain.dto.CmsServiceQueryCriteria;
import com.fzhucc.modules.appletShow.service.CmsServiceService;
import com.fzhucc.modules.expert.domain.dto.ExpertCountQueryCriteria;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.thinktank.domain.dto.AllBindDto;
import com.fzhucc.utils.JwtSecurityUtils;
import com.fzhucc.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * @author woolsen
 * @since 2022-11-16
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "服务展示:管理")
@RequestMapping("/api/cms/service")
public class CmsServiceController {

    private final CmsServiceService cmsServiceService;

    private final UserRepository userRepository;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('cms:service:list')")
    public void exportAppletShow(HttpServletResponse response, CmsServiceQueryCriteria criteria) throws IOException {
        cmsServiceService.download(cmsServiceService.queryAll(criteria), response);
    }


    @Log("查询服务展示")
    @ApiOperation("查询服务展示")
    @AnonymousGetMapping("/show")
    public ResponseEntity<Object> queryAppletShow(CmsServiceQueryCriteria criteria, Pageable pageable) {
        if (!JwtSecurityUtils.hasAuthority("cms:service:list")) { //服务项目 没权限  赋予最低level查询条件
            criteria.setLevel(1);
        } else {//服务项目 登录用户  根据level查询条件
            Long userId = SecurityUtils.getCurrentUserId();
            Optional<User> res = userRepository.findById(userId);
            if (res.isPresent()) {
                User user = res.orElseGet(User::new);
                criteria.setLevel(user.getProjectLevel());
            }
        }
        /*criteria.setLevel(null);*/
        return new ResponseEntity<>(cmsServiceService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("查询单条服务展示")
    @ApiOperation("查询单条服务展示")
    @AnonymousGetMapping("/id/{id}")
    public ResponseEntity<Object> queryById(@PathVariable Integer id) {
        return new ResponseEntity<>(cmsServiceService.findById(id), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增服务展示")
    @ApiOperation("新增服务展示")
    @PreAuthorize("@el.check('cms:service:add')")
    public ResponseEntity<Object> createAppletShow(@Validated @RequestBody CmsServiceDto resources) {
        return new ResponseEntity<>(cmsServiceService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改服务展示")
    @ApiOperation("修改服务展示")
    @PreAuthorize("@el.check('cms:service:edit')")
    public ResponseEntity<Object> updateAppletShow(@Validated @RequestBody CmsServiceDto resources) {
        cmsServiceService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除服务展示")
    @ApiOperation("删除服务展示")
    @PreAuthorize("@el.check('cms:service:del')")
    public ResponseEntity<Object> deleteAppletShow(@RequestBody Integer[] ids) {
        cmsServiceService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("上传Banner图")
    @PostMapping(value = "/uploadPhoto")
    public ResponseEntity<Object> uploadPhoto(@RequestParam MultipartFile photo, @RequestParam Integer id) {
        return new ResponseEntity<>(cmsServiceService.douploadpic(photo, id), HttpStatus.OK);
    }

    @Log("查询服务分类数量")
    @ApiOperation("查询服务分类数量")
    @AnonymousPostMapping("/getCountByClassify")
    public ResponseEntity<Object> getCountByClassify() {
        return new ResponseEntity<>(cmsServiceService.getCountByClassify(), HttpStatus.OK);
    }
    @GetMapping(value = "/getType")
    @Log("获取服务分类")
    @ApiOperation("获取服务分类")
    @AnonymousAccess
    public ResponseEntity<Object> getType() {
        return new ResponseEntity<>(cmsServiceService.getType(),HttpStatus.OK);
    }


    @ApiOperation("生成服务详情小程序码")
    @Log("生成服务详情小程序码")
    @AnonymousAccess
    @PostMapping(value = "/generateQrCode")
    public AllBindDto generateQrCode(@RequestBody CmsServiceCodeDto dto) {
        return cmsServiceService.generateQrCode(dto);
    }
}